package com.cqie.secondhandtransaction.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.secondhandtransaction.DTO.DataList;
import com.cqie.secondhandtransaction.DTO.OrderDTO;
import com.cqie.secondhandtransaction.DTO.OrderInfoVO;
import com.cqie.secondhandtransaction.DTO.UserDetailsDTO;
import com.cqie.secondhandtransaction.entity.OrderInfo;
import com.cqie.secondhandtransaction.entity.ProductInfo;
import com.cqie.secondhandtransaction.entity.UserInfo;
import com.cqie.secondhandtransaction.enums.OrderStatusEnum;
import com.cqie.secondhandtransaction.enums.RoleEnum;
import com.cqie.secondhandtransaction.enums.StatusEnum;
import com.cqie.secondhandtransaction.exception.BusinessException;
import com.cqie.secondhandtransaction.mapper.OrderInfoMapper;
import com.cqie.secondhandtransaction.mapper.ProductInfoMapper;
import com.cqie.secondhandtransaction.mapper.UserInfoMapper;
import com.cqie.secondhandtransaction.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.secondhandtransaction.service.ProductInfoService;
import com.cqie.secondhandtransaction.utils.DateUtil;
import com.cqie.secondhandtransaction.utils.WebSecurityUtil;
import com.github.xiaoymin.knife4j.core.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-10
 */
@Slf4j
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private ProductInfoService productInfoService;

    @Override
    public DataList<OrderInfoVO> orderList(String status, boolean isSeller) {
        UserDetailsDTO user = WebSecurityUtil.getCurrentUser();
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();

        //根据用户查询
        if(isSeller)
            //卖出的
            queryWrapper.eq(OrderInfo::getSallerId, user.getId());
        else
            //买到的
            queryWrapper.eq(OrderInfo::getUserId, user.getId());

        //根据状态查询
        if(StringUtils.hasText(status))
            queryWrapper.eq(OrderInfo::getStatus, status);


        queryWrapper.orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> orders = orderInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(orders)) {
            return new DataList<>();
        }
        DataList<OrderInfoVO> dataList = new DataList<>();
        List<OrderInfoVO> voList = new ArrayList<>();
        for (OrderInfo order : orders) {
            OrderInfoVO orderInfoVO = new OrderInfoVO();
            BeanUtils.copyProperties(order, orderInfoVO);
            //查询商家信息
            UserInfo sallor = userInfoMapper.selectById(order.getSallerId());
            orderInfoVO.setSaller(sallor);
            //查询买家信息
            orderInfoVO.setUserInfo(user.toUserInfo());
            //查询商品信息
            orderInfoVO.setProductInfo(productInfoService.getProductDetail(order.getProductId()));
            voList.add(orderInfoVO);
        }
        dataList.setDataList(voList);
        return dataList;
    }

    /**
     * 创建订单
     *
     * @param dto
     */
    @Transactional
    @Override
    public void startOrder(OrderDTO dto) {
        UserDetailsDTO user = WebSecurityUtil.getCurrentUser();

        Assert.isTrue(Objects.equals(dto.getSallerId(), user.getId()), "不能购买自己的商品！");

        OrderInfo orderInfo = new OrderInfo();
        StringBuilder orderCode =  new StringBuilder("O_" + DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.DATE_PATTERN.YYYYMMDD));
        //查询最新的数据
        OrderInfo order = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().orderByDesc(OrderInfo::getId).last("limit 1"));
        if (Objects.isNull(order)) {
            orderCode.append("0001");
        } else {
            int nextOrderNumber = Integer.parseInt(order.getOrderCode().substring(10)) + 1;
            orderCode.append(String.format("%04d", nextOrderNumber));
        }
        orderInfo.setOrderCode(orderCode.toString());
        orderInfo.setSallerId(dto.getSallerId());
        orderInfo.setUserId(user.getId());
        orderInfo.setProductId(dto.getProductId());
        orderInfo.setOrdAddress(dto.getOrdAddress());
        ProductInfo productInfo = productInfoMapper.selectById(dto.getProductId());
        if (Objects.nonNull(productInfo) && productInfo.getCount() == 0) {
            throw new BusinessException("该商品已被其他用户交易，请重新寻找心仪物品，感谢您的光临！");
        }

        //插入订单信息（暂时不提交，等待支付成功后再提交）
        orderInfo.setStatus(OrderStatusEnum.PENDING.getCode()); // 设置为待支付状态
        orderInfoMapper.insert(orderInfo);

        //支付逻辑
        try {
            this.pay(orderCode.toString(), productInfo.getPrice());
        } catch (Exception e) {
            throw new BusinessException("支付过程中发生错误：" + e.getMessage());
        }
    }

    /**
     * 假支付
     *
     * @param orderCode
     * @param price
     */
    @Override
    @Transactional
    public void pay(String orderCode, BigDecimal price) {
        //更新订单状态为已支付
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderCode, orderCode));
        if (orderInfo != null) {
            orderInfo.setStatus(OrderStatusEnum.PAID.getCode());
            orderInfo.setOrdPrice(price);
            orderInfoMapper.updateById(orderInfo);

            //更新商品库存
            ProductInfo productInfo = productInfoMapper.selectById(orderInfo.getProductId());
            if (productInfo != null) {
                productInfo.setCount(productInfo.getCount() - 1);
                if (productInfo.getCount() == 0)
                    productInfo.setStatus(StatusEnum.SOLD_OUT.getCode());

                productInfoMapper.updateById(productInfo);
                log.info("支付成功，订单号：{}", orderCode);

                //更新商家销量
                UserInfo userInfo = userInfoMapper.selectById(productInfo.getSallorBy());
                userInfo.setSoldNum(userInfo.getSoldNum() + 1);
                userInfoMapper.updateById(userInfo);
            }
        }

    }

    /**
     * 删除订单
     *
     * @param orderCode
     */
    @Override
    public void deleteOrder(String orderCode) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderCode, orderCode));

        UserDetailsDTO user = Objects.nonNull(WebSecurityUtil.getCurrentUser()) ? WebSecurityUtil.getCurrentUser() : new UserDetailsDTO();

        if (Objects.equals(user.getRole(), RoleEnum.ADMIN.getRole())) {
            //管理员可以直接删除
            orderInfoMapper.deleteById(orderInfo.getId());
        } else if (Objects.equals(orderInfo.getUserId(), user.getId()) && Objects.equals(orderInfo.getStatus(), OrderStatusEnum.PAID.getCode())) {
            orderInfoMapper.deleteById(orderInfo.getId());
        } else {
            throw new BusinessException("删除失败！");
        }

    }

    /**
     * 更新商品状态
     *
     * @param dto
     */
    @Override
    @Transactional
    public void updateOrderStatus(OrderDTO dto) {
        OrderInfo orderInfo = Optional.ofNullable(orderInfoMapper.selectById(dto.getId()))
                .orElseThrow(() -> new BusinessException("订单不存在！"));

        orderInfo.setStatus(dto.getStatus().getCode());
        orderInfoMapper.updateById(orderInfo);
    }
}
